/**
 * 
 */
package cn.xiaolang.thread.wait;

import java.util.concurrent.CountDownLatch;

/**
 * countDownLatch方式处理线程等待其他线程
 * 
 * @author fuhw
 * @date 2017年8月17日 上午10:13:32
 */
public class ThreadWaitByCountDownLatch {

	private static final CountDownLatch countDownLatch = new CountDownLatch(10);//倒序计时器

	/**
	 * 
	 * 执行结果：
	 * <p>
	 * start create some thread: Thread-0executing..... Thread-1executing.....
	 * Thread-2executing..... Thread-3executing..... Thread-4executing.....
	 * Thread-5executing..... Thread-6executing..... Thread-7executing.....
	 * Thread-8executing..... Thread-9executing..... all thread execute over!
	 * 
	 * </p>
	 * 如果取消：Thread.join();//那么执行结果的顺序是不可预测的
	 * <p>
	 * start create some thread: all thread execute over! Thread-2executing.....
	 * Thread-3executing..... Thread-1executing..... Thread-4executing.....
	 * Thread-5executing..... Thread-6executing..... Thread-7executing.....
	 * Thread-8executing..... Thread-9executing..... Thread-0executing.....
	 * </p>
	 */
	public static void main(String[] args) throws InterruptedException {

		System.err.println("start create some thread:");
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				// do-something
				try {
					Thread.sleep(1);
					System.err.println(Thread.currentThread().getName() + "executing.....");
					countDownLatch.countDown();// 注意：countDownLatch的位置，在run执行完成
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}).start();
		}
		countDownLatch.await();
		System.err.println("all thread execute over!");
	}

}
